package cn.wildfire.chat.app.extendsion.utils;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * Create by HEKE, 2019/8/19 18:27
 * TODO 基本沙盒存储文件操作对象
 */
public class SPUtils {

    /**
     * 设置单个参数文本内容
     *
     * @param context
     * @param spName
     * @param key
     * @param value
     */
    public static void setSingle(Context context, String spName, String key, String value) {
        try {
            SharedPreferences sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putString(key, value);
            editor.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置单个参数文本内容
     *
     * @param context
     * @param spName
     * @param key
     */
    public static String getSingle(Context context, String spName, String key) {
        String value = null;
        try {
            SharedPreferences sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
            value = sp.getString(key, "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 设置多个参数文本内容
     *
     * @param context
     * @param spName
     * @param keys
     * @param values
     */
    public static void setMuches(Context context, String spName, String[] keys, String[] values) {
        if (keys == null || values == null) {
            return;
        }
        if (keys.length != values.length) {
            throw new ArithmeticException("### Case : The length of keys not the same with values !");
        }
        try {
            SharedPreferences sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            for (int i = 0; i < keys.length; i++) {
                String key = keys[i];
                String value = values[i];
                editor.putString(key, value);
            }
            editor.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取多个参数文本内容
     *
     * @param context
     * @param spName
     * @param keys
     */
    public static String[] getMuches(Context context, String spName, String[] keys) {
        if (keys == null) {
            return null;
        }
        String[] values = new String[keys.length];
        try {
            SharedPreferences sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
            for (int i = 0; i < keys.length; i++) {
                String key = keys[i];
                values[i] = sp.getString(key, "");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return values;
    }

}
